package api

import (
	st "RemedialClass/common"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"math"
	"net/http"
	"strconv"
)

func DB() {
	// 建立数据库连接
	dsn := "root:root123@tcp(124.220.93.86:3306)/123?charset=utf8mb4&parseTime=True&loc=Local" // 替换为你的数据库连接信息
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}
	classID := uuid.New().String()
	fmt.Println(classID)
	err = db.AutoMigrate(&st.Class{}, &st.Student{})
	if err != nil {
		log.Fatal(err)
	}

	r := gin.Default()

	// 新建班级
	r.POST("/classes", func(c *gin.Context) {
		var class st.Class
		if err := c.ShouldBindJSON(&class); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// 检查是否存在相同的className
		var count int64
		if err := db.Model(&st.Class{}).Where("CONVERT(class_name USING utf8mb4) = ?", class.ClassName).Count(&count).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database"})
			return
		}

		if count > 0 {
			c.JSON(http.StatusConflict, gin.H{"message": "班级已存在"})
			return
		}

		// 继续处理新增班级逻辑
		class.ClassID = uuid.New().String()

		result := db.Create(&class)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": result.Error,
			})
			return
		}
		c.JSON(http.StatusOK, class)
	})

	// 新增学生
	r.POST("/students", func(c *gin.Context) { //新增学生
		var student st.Student
		if err := c.ShouldBindJSON(&student); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		// 检查是否存在相同的Phone
		var count int64
		if err := db.Model(&st.Student{}).Where("CONVERT(phone USING utf8mb4) = ?", student.Phone).Count(&count).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database"})
			return
		}

		if count > 0 {
			c.JSON(http.StatusConflict, gin.H{"message": "学生已存在"})
			return
		}

		result := db.Create(&student)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error})
			return
		}

		c.JSON(http.StatusOK, student)
	})

	// 查询班级
	r.GET("/class/list", func(c *gin.Context) { // 分页查询班级
		var classes []st.Class
		var count int64

		page, _ := strconv.Atoi(c.Query("page"))
		pageSize, _ := strconv.Atoi(c.Query("pageSize"))

		db.Offset((page - 1) * pageSize).Limit(pageSize).Find(&classes)
		db.Model(&st.Class{}).Count(&count)

		c.JSON(http.StatusOK, gin.H{
			"data":      classes,
			"total":     count,
			"page":      page,
			"pageSize":  pageSize,
			"totalPage": math.Ceil(float64(count) / float64(pageSize)),
		})
	})

	//查询班级下的学生
	r.GET("/students/list", func(c *gin.Context) {
		classID := c.Query("classID")
		page, _ := strconv.Atoi(c.Query("page"))
		pageSize, _ := strconv.Atoi(c.Query("pageSize"))

		var students []st.Student
		var count int64

		result := db.Where("class_id = ?", classID).Find(&students)

		offset := (page - 1) * pageSize
		db.Where("class_id = ?", classID).Offset(offset).Limit(pageSize).Find(&students)

		db.Model(&st.Student{}).Where("class_id = ?", classID).Count(&count)

		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"data":      students,
			"total":     count,
			"page":      page,
			"pageSize":  pageSize,
			"totalPage": math.Ceil(float64(count) / float64(pageSize)),
		})
	})

	// 修改学生信息(变更学生状态，课时，金额)
	r.PUT("/students/:phone", func(c *gin.Context) {
		phone := c.Param("phone")
		var student st.Student
		if err := db.Where("phone = ?", phone).First(&student).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "暂无此学生"})
			return
		}

		// 解析请求体中的新数据并更新学生信息
		if err := c.ShouldBindJSON(&student); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// 根据status字段的值返回相应的状态字符串
		switch student.Status {
		case "0":
			student.Status = "到课"
		case "1":
			student.Status = "迟到"
		case "2":
			student.Status = "请假"
		case "3":
			student.Status = "未到"
		default:
			student.Status = ""
		}

		result := db.Save(&student)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "学生信息修改成功",
			"data":    student,
		})
	})

	r.Run(":9090")
}
